package com.dongbao.action;

import com.alibaba.fastjson.JSONObject;
import com.dongbao.date.DateCentre;
import com.dongbao.dialog.ChooseTemplateDialog;
import com.dongbao.dialog.InputCodeDialog;
import com.dongbao.dialog.InputDialog;
import com.dongbao.module.TemplateDto;
import com.dongbao.utils.HttpClientUtils;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ValidationInfo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class PropAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {

        //获取当前编辑器对象
        Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
        //获取选择的数据模型
        SelectionModel selectionModel = editor.getSelectionModel();
        //获取当前选择的文本 并且去除首位的双引号与单引号
        String selectedText = selectionModel.getSelectedText().replace("\'","").replace("\"","");

        /* 打开弹窗让输入系统Code与多语言Code */
        InputCodeDialog inputCodeDialog = new InputCodeDialog("输入多语言Code",selectedText);
        String code = "";
        if (inputCodeDialog.showAndGet()) {
            // 点击确定后执行逻辑
            // 获取输入内容
            DateCentre.hsot = inputCodeDialog.getHostInputInput().getText();
            DateCentre.sysCode = inputCodeDialog.getSysCodeInput().getText();
            DateCentre.code = inputCodeDialog.getCodeInput().getText();
            DateCentre.isDefault = inputCodeDialog.getisDefaultCheckBox().isSelected()?"1":"0";

            /* 调用DHG服务接口 返回占位符字符串替换进去 */
            int selectionStart = selectionModel.getSelectionStart();
            VisualPosition selectionStartPosition = selectionModel.getSelectionStartPosition();

            WriteCommandAction.runWriteCommandAction(e.getProject(), new Runnable() {
                @Override
                public void run() {
                    /* 调用接口获取多语言数据 */
                    InetAddress addr = null;
                    try {
                        addr = InetAddress.getLocalHost();
                    } catch (UnknownHostException ex) {
                        ex.printStackTrace();
                    }
                    StringBuffer url = new StringBuffer();
                    url.append(DateCentre.hsot);
                    url.append("/sysLocalesInfo/ideaQuerySysLog?");
                    try {
                        url.append("content=" +  URLEncoder.encode(selectedText, "UTF-8"));
                    } catch (UnsupportedEncodingException ex) {
                        ex.printStackTrace();
                    }
                    url.append("&ip=" + addr.getHostAddress());
                    url.append("&systemCode=" + DateCentre.sysCode);
                    url.append("&code=" + DateCentre.code);
                    url.append("&type=" + DateCentre.isDefault);
                    JSONObject jsonObject = HttpClientUtils.httpGet(url.toString());

                    if(null == jsonObject || "".equals(jsonObject)){
                        ValidationInfo validationInfo = new ValidationInfo("请检查配置的地址是否正确【"+DateCentre.hsot+"/sysLocalesInfo/ideaQuerySysLog】");
                        Messages.showMessageDialog(validationInfo.message,"提示", Messages.getInformationIcon());
                        /* 既然连接错误就把他清空,再次使用时会提示重新输入地址 */
                        DateCentre.hsot = null;
                    }else{
                        JSONObject data = (JSONObject)jsonObject.getInnerMap().get("data");
                        /* 根据文件名后缀获取到应该填充什么表达式 */
                        String result = "";
                        String defaultExtension = ((EditorImpl) editor).getVirtualFile().getFileType().getDefaultExtension();
                        if(defaultExtension.equals("java")){
                            result = String.valueOf(data.get("java"));
                        }else if(defaultExtension.equals("html")){
                            result = String.valueOf(data.get("web"));
                        }else if(defaultExtension.equals("js")){
                            result = String.valueOf(data.get("js"));
                        }else if(defaultExtension.equals("vue")||defaultExtension.equals("txt")){
                            /* 增加弹窗选择勾选使用哪个模板 */
//                            result = String.valueOf(data.get("js"));
                            TemplateDto templateDto = new TemplateDto();
                            templateDto.setJavaTemplate(String.valueOf(data.get("java")));
                            templateDto.setHtmlTemplate(String.valueOf(data.get("web")));
                            templateDto.setJsTemplate(String.valueOf(data.get("js")));
                            templateDto.setOrgTemplate(String.valueOf(data.get("template")));
                            ChooseTemplateDialog chooseTemplateDialog = new ChooseTemplateDialog(templateDto);
                            if (chooseTemplateDialog.showAndGet()) {
                                /* 获取选择的值 */
                                result = chooseTemplateDialog.getCheckValue();
                            }
                        }
                        if(result == ""){
                            ValidationInfo validationInfo = new ValidationInfo("当前打开文件类型未查找到对应多语言标签,请检查DHG是否支持！");
                            Messages.showMessageDialog(validationInfo.message,"提示", Messages.getInformationIcon());
                        }else{
                            //是否还需要生成
                            Boolean isGener = true;

                            //获取上一个换行符的位置
                            int rowNum = editor.getDocument().getText().substring(0, selectionModel.getSelectionStart()).lastIndexOf("\n");
                            if(result.indexOf("ToolUtil.getLocaleValue")==0){
                                //判断多语言中是否存在变量,如果存在变量则将变量取出,声明一个Map转换
                                if(selectedText.indexOf("${")!=-1){
                                    isGener = false;
                                    //使用正则表达式提取出变量
                                    final Pattern pattern = Pattern.compile("\\$\\{[\\s|\\t|\\r|\\n]+.*?\\}");
                                    List<String> existParams = Collections.synchronizedList(new ArrayList<>());
                                    Matcher matcher = Pattern.compile("\\{([^}]*)\\}").matcher(selectedText);
                                    int matcher_start = 0;
                                    while (matcher.find(matcher_start)){
                                        existParams.add(matcher.group(1));
                                        matcher_start = matcher.end();
                                    }
                                    //声明Map插入
                                    StringBuilder sb = new StringBuilder();
                                    sb.append("//" + selectedText);
                                    sb.append("\n");
                                    sb.append("Map<String,Object> map = new HashMap<>();");
                                    sb.append("\n");
                                    for(String param:existParams){
                                        sb.append("map.put(\""+param+"\",\"******\");");
                                        sb.append("\n");
                                    }
                                    editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(),"ToolUtil.getTemplateValue(" + result.replace(";","") + ",map)");
                                    editor.getDocument().replaceString(rowNum, rowNum,"\n // " + sb.toString() + "  ");
                                }else{
                                    editor.getDocument().replaceString(rowNum, rowNum,"\n // " + selectedText + "  ");
                                }
                            }else if(result.indexOf("{{$t(")==0){
                                editor.getDocument().replaceString(rowNum, rowNum,"\n <!-- " + selectedText + " --> ");
                            }else if(result.indexOf("$t(")==0){
                                editor.getDocument().replaceString(rowNum, rowNum,"\n // " + selectedText  );
                            }else if(result.indexOf("$t{tool.getLocaleValue")==0){
                                editor.getDocument().replaceString(rowNum, rowNum,"\n <!-- " + selectedText + " --> ");
                            }
                            if(isGener){
                                editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(),result);
                            }
                            selectionModel.removeSelection();
                        }
                    }

                }
            });
        }


    }

    public static void main(String[] args) {
        String testStr = "44564564q中文werwer测试asdas哈哈哈";
    }
}
